<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTool>
        <template #before>
          <span>共{{ page.total }}条数据</span>
        </template>
        <template #after>
          <el-button type="danger" size="small" @click="onExport">导出Excel表格</el-button>
          <el-button type="primary" size="small" @click="$router.push('/import')">导入Excel表格</el-button>
          <el-button type="success" size="small" @click="showAddDialog=true">新增员工</el-button>

        </template>
      </PageTool>
      <!-- 表格区域 -->
      <el-card>
        <el-table :data="list" border stripe>
          <!-- <el-table-colum[label="" :sortable="true" prop=""]*10 -->
          <el-table-column label="序号" :sortable="true" type="index" width="50"></el-table-column>
          <el-table-column label="姓名" :sortable="true" prop="username"></el-table-column>
          <el-table-column label="头像" :sortable="true" prop="staffPhoto" width="130">
            <!-- 头像用作用于插槽显示 -->
            <template v-slot="{row}">
              <!-- <img
                v-imgerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                style="width:100px;height:100px;border-radius:50%"
              /> -->
              <!-- 使用组件显示头像 -->
              <el-image :src="row.staffPhoto" @click="onShowErCodeDialog(row.staffPhoto)">
                <img slot="error" src="@/assets/common/head.jpg" @click="onShowErCodeDialog(require('@/assets//common/head.jpg'))">
              </el-image>
            </template>
            <!-- 头像用作用于插槽显示 -->

          </el-table-column>
          <el-table-column label="手机号" :sortable="true" prop="mobile"></el-table-column>
          <el-table-column label="工号" :sortable="true" prop="workNumber"></el-table-column>
          <el-table-column label="聘用形式" :sortable="true" prop="formOfEmployment">
            <template v-slot="{row}">

              {{ row.formOfEmployment | formatHireType }}

            </template>

          </el-table-column>
          <el-table-column label="部门" :sortable="true" prop="departmentName"></el-table-column>
          <el-table-column label="入职时间" :sortable="true" prop="timeOfEntry">
            <!-- 使用作用于插槽过滤时间 -->
            <template v-slot="{row}">
              <!-- 使用过滤器 -->
              {{ row.timeOfEntry | formatdate }}
            </template>
          </el-table-column>
          <el-table-column label="状态" :sortable="true" prop="enableState">

            <template v-slot="{row}">
              <el-switch v-model="row.enableState" disabled :active-value="1" :inactive-value="0"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" :sortable="true" prop="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" @click="$router.push('/employee/detail/' + row.id)">查看</el-button>
              <el-button type="text">转正</el-button>
              <el-button type="text">调岗</el-button>
              <el-button type="text">离职</el-button>
              <el-button type="text">角色</el-button>
              <el-button type="text" @click="onDel(row.id)">删除</el-button>

            </template>
          </el-table-column>

        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next"
            :page-size="page.size"
            :total="page.total"
            @current-change="onPageChange"
          >
          </el-pagination>
        </el-row>
        <!-- 分页 -->

      </el-card>
      <!-- 表格区域 -->

    </div>
    <!-- 二维码对话框展示区 -->
    <!-- <el-dialog title="展示二维码" :visible="showErCodeDialog" @close="showErCodeDialog=false">

    </el-dialog> -->
    <el-dialog title="展示二维码" :visible.sync="showErCodeDialog">
      <qrcode-vue :value="value" :size="size" level="H"></qrcode-vue>
    </el-dialog>

    <!-- 二维码对话框展示区 -->

    <!-- 新增员工对画框 -->
    <el-dialog v-if="showAddDialog" :visible="showAddDialog" v-bind="$attrs" title="新增员工" v-on="$listeners" @open="onOpen" @close="close">
      <el-form ref="formRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入姓名" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="入职时间" prop="timeOfEntry">
          <el-date-picker
            v-model="form.timeOfEntry"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :style="{width: '100%'}"
            placeholder="请选择入职时间"
            clearable
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="聘用形式" prop="formOfEmployment">
          <el-select v-model="form.formOfEmployment" placeholder="请选择聘用形式" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in formOfEmploymentOptions"
              :key="index"
              :label="item.value"
              :value="item.id"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工号" prop="workNumber">
          <el-input v-model="form.workNumber" placeholder="请输入工号" clearable :style="{width: '100%'}"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入部门" clearable :style="{width: '100%'}" @focus="getdeptsList">
          </el-input>
          <el-tree
            v-if="showTree"
            :data="deptsList"
            :props="{label:'name'}"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-form-item>
        <el-form-item label="转正时间" prop="correctionTime">
          <el-time-picker
            v-model="form.correctionTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            :picker-options="{&quot;selectableRange&quot;:&quot;00:00:00-23:59:59&quot;}"
            :style="{width: '100%'}"
            placeholder="请选择转正时间"
            clearable
          ></el-time-picker>
        </el-form-item>
      </el-form>
      <el-row
        slot="footer"
        type="flex"
        justify="center"
      >
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </el-row>
    </el-dialog>

  </div>
</template>

<script>
import { addEmployee, delEmployee, getEmployees } from '@/api/Employees'
import QrcodeVue from 'qrcode.vue'
import EmployeeEnum from '@/api/constant/employees.js'
import { getDeptsListAPI } from '@/api/departments'
import { translateListToTree } from '@/utils'
import { pick } from 'lodash'// 按需引入lodash数据处理方法
import { formatdate, formatHireType } from '../../../src/components/filters/index.js'
export default {
  name: 'EmployeePgae',
  components: { QrcodeVue },
  props: {
  },
  data() {
    return {
      list: [], // 定义列表数据
      value: 'https://example.com',
      size: 300,
      page: { // 定义分页信息
        page: 1,
        size: 2,
        total: 0
      },
      showErCodeDialog: false, // 定义控制二维码展示变量
      staffPhotoUrl: undefined, // 头像图片的地址
      form: {
        username: undefined,
        mobile: undefined,
        timeOfEntry: null,
        formOfEmployment: undefined,
        workNumber: undefined,
        departmentName: undefined,
        correctionTime: null
      },
      rules: {
        username: [{
          required: true,
          message: '请输入姓名',
          trigger: 'blur'
        }],
        mobile: [{
          required: true,
          message: '请输入手机',
          trigger: 'blur'
        }],
        timeOfEntry: [{
          required: true,
          message: '请选择入职时间',
          trigger: 'change'
        }],
        formOfEmployment: [{
          required: true,
          message: '请选择聘用形式',
          trigger: 'change'
        }],
        workNumber: [{
          required: true,
          message: '请输入工号',
          trigger: 'blur'
        }],
        departmentName: [{
          required: true,
          message: '请输入部门',
          trigger: 'change'// 将校验时机从blur换成change
        }],
        correctionTime: []
      },
      formOfEmploymentOptions: EmployeeEnum.hireType,
      // [{
      //   'label': '选项一',
      //   'value': 1
      // }, {
      //   'label': '选项二',
      //   'value': 2
      // }],
      showAddDialog: false,
      deptsList: [], // 定义获取部门的变量
      showTree: false// 定义控制树展开关闭的变量
    }
  },
  created() {
    this.getEmployeeList()
  },
  mounted() {},
  methods: {
    onDel(id) { // 删除
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        await delEmployee(id)// 发请求
        this.$message.success('删除成功')
        this.getEmployeeList()// 刷新列表
      })
    },
    handleNodeClick(data) {
      this.form.departmentName = data.name// 保存部门名称,隐藏树
      this.showTree = false// 关闭
    },
    async getEmployeeList() { // 定义获取员工列表数据的方法
      // const res = await getEmployees(this.page)
      const { total, rows } = await getEmployees(this.page)
      this.page.total = total
      this.list = rows
    },
    onPageChange(val) {
      this.page.page = val
      this.getEmployeeList()
    },
    onShowErCodeDialog(url) {
      this.staffPhotoUrl = url
      this.showErCodeDialog = true
    },
    onOpen() {},

    close() {
      this.$refs['formRef'].resetFields()
      this.showAddDialog = false
    },
    handelConfirm() {
      this.$refs['formRef'].validate(async valid => { // 添加员工确定操作调用接口
        if (!valid) return
        await addEmployee(this.form)// 发请求
        this.$message.success('添加成功')// 成功提示
        this.getEmployeeList()// 刷新数据
        //
        this.close()
      })
    },
    async getdeptsList() { // 获取部门名称数据
      // const { depts } = await getDeptsListAPI()
      // this.deptsList = translateListToTree(depts, '')
      this.showTree = true// 焦点集中显示树
      try {
        const { depts } = await getDeptsListAPI()

        this.deptsList = translateListToTree(depts, '')
      } catch (error) {
        console.log(error)
      }
    },
    onExport() { // 导出表格内容
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = { // 定义中间变量
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const { rows } = await getEmployees({ // 获取所有用户的数据

          page: 1,
          size: this.page.total
        })

        // 完整写法--做数据转换（推荐使用完整写法）
        const values = Object.values(headers)

        const data = rows.map(t => { // 转换数据
          const item = pick(t, values)
          item.timeOfEntry = formatdate(item.timeOfEntry)
          item.correctionTime = formatdate(item.correctionTime)

          item.formOfEmployment = formatHireType(item.formOfEmployment)

          return Object.values(item)
        })
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填一维数组
          data: data, // 具体数据 必填 二维数组
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
